package cn.gmcx.lazy.izze.service.impl;

import cn.gmcx.lazy.izze.exception.BizException;
import cn.gmcx.lazy.izze.pojo.User;
import cn.gmcx.lazy.izze.mapper.UserMapper;
import cn.gmcx.lazy.izze.service.IUserService;
import cn.gmcx.lazy.izze.utils.JwtUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author GMCX
 * @since 2024-06-14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void add(String fileUrl, User user) {
        user.setAvatar(fileUrl);

        Random random = new Random();
        int randomNumber = random.nextInt(900000) + 10000;
        String IzzeCode = String.valueOf(randomNumber);
        user.setIzzeCode(IzzeCode);
        userMapper.add(user);
    }


    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }
    @Override
    public List<User> selectAll() {
        List<User> users = userMapper.selectAll();
        return users;
    }
    @Override
    public User selectById(Integer id) {
        List<Integer> parise = userMapper.selectParise(id);
        Integer sum=0;
        for (Integer integer : parise) {
            sum+=integer;
        }
        User user = userMapper.selectById(id);
        user.setPraise(sum);
        return user;
    }
    @Override
    public String select_user(User user) {
        Map<String,String> map = new HashMap<>();
        String token;
        User user_message = userMapper.select_user(user);
        if (user_message != null){
            map.put("id",user_message.getId().toString());
            token = JwtUtils.ToJwt(map);
            return token;
        }else{
            throw new BizException("用户名或密码错误");
        }
    }
    @Override
    public User selectId(String id) {
        User user = userMapper.selectId(id);
        return user;
    }

}
